import { _decorator, Button, find, Label, tween, Tween, UITransform } from 'cc';
import { BasePopUp } from '../../../frame/component/ui.pop-up';
import { ClientAPI } from '../../api/api.client';
import GameDC from '../../data/data.game.center';
import DataManager from '../../manager/data.manager';
import type { Popup } from '../page/pop-up';
const { ccclass, property } = _decorator;

@ccclass('ppTreasureBox')
export class ppTreasureBox extends BasePopUp<typeof Popup, boolean> {
	protected default_return: null;

	private ui_ligth: UITransform;
	private contianer: UITransform;
	private icon_diamond: UITransform;

	private lock: boolean;

	protected initAfterOnLoad(){
		this.init();
		this.initUIStatus();
		this.renderLocalUI();
	}

	public onShow(){
		GameDC.Trigger.HILIT_DIAMOND = true;
		BasePopUp.jelly_enter(this.contianer.node);

		Tween.stopAllByTarget(this.ui_ligth.node);
		tween(this.ui_ligth.node).set({angle: 0})
		.to(5, {angle: -360}).union()
		.repeatForever().start();
	}

	private init(){
		this.lock = false;
		let node_box = this.node.getChildByName('box');
		this.ui_ligth = node_box.getChildByName('light').getComponent(UITransform);
		this.contianer = node_box.getChildByName('container').getComponent(UITransform);
		this.icon_diamond = this.contianer.node.getChildByName('icon-diamond').getComponent(UITransform);
	}

	private initUIStatus(){
		this.ui_ligth.node.angle = 0;
	}

	private renderLocalUI(){
		(<const>[
			['lbl-head', 'Lucky Rewards'],
			['lbl-reap', 'CLAIM'],
			['close', 'No Thanks'],
			['lbl-desc', '3 diamonds']
		]).forEach(([name, text])=>this.contianer.node.getChildByName(name).getComponent(Label).string = text);

		find('diamond/lbl-value', this.contianer.node).getComponent(Label).string = 'x3';
	}

	protected _click_event_: { [name: string]: (this: ppTreasureBox, button: Button) => void; } = {
		close(btn){
			if(this.lock){
				return void 0;
			}
			this.lock = true;

			btn.interactable = false;
			this.exit(false, btn);
		},
		reap(btn){
			if(this.lock){
				return void 0;
			}
			this.lock = true;

			btn.interactable = false;
			ClientAPI.AD('incentive').then(success=> this.exit(success, btn) );
		}
	}

	private exit(reap: boolean, btn: Button){
		if(reap){
			DataManager.floatDiamond(3, this.icon_diamond.node.worldPosition);
		}
		BasePopUp.jelly_leave(this.contianer.node)
		.then(()=>{
			this.close(reap);
			btn.interactable = true;
			this.lock = false;
			Tween.stopAllByTarget(this.ui_ligth.node);
			this.ui_ligth.node.angle = 0;
			GameDC.Trigger.HILIT_DIAMOND = false;
		});
	}
}
